<template>
  <div class="sys-init-container">
    <el-container>
      <el-header class="sys-init-header">
        <h1>系统初始化</h1>
      </el-header>
      <el-main>
        <el-row>
          <el-col :span="4"></el-col>
          <el-col :span="16">
            <div class="sys-init-content">
              <el-steps :active="active" finish-status="success" class="sys-init-steps">
                <el-step title="数据库选择" />
                <el-step title="账号配置" />
                <el-step title="完成" />
              </el-steps>

              <el-divider />
              <el-form :model="form" class="sys-init-form">
                <div v-if="active === 0" class="form-section">
                  <div class="section-title">数据库配置</div>
                  <div class="section-content">
                    <el-form-item label="数据库类型" required>
                      <el-radio-group v-model="form.db_type" class="db-type-radio">
                        <el-radio v-if="false" value="sqlite">SQLite</el-radio>
                        <el-radio value="mysql">MySQL</el-radio>
                        <el-radio value="pgsql">PostgresSQL</el-radio>
                      </el-radio-group>
                    </el-form-item>

                    <el-form-item v-if="form.db_type === 'sqlite'" class="dsn-form-item">
                      <el-card class="dsn-card">
                        <template #header>
                          <div class="card-header">
                            <span>样例:&nbsp;&nbsp;gowebssh.db</span>
                          </div>
                        </template>
                        <el-input v-model="form.mysql_dbdsn" minlength="10" maxlength="65535" show-word-limit clearable
                          placeholder="请输入数据库DSN,参考上面的样例" class="dsn-input">
                          <template #prefix>
                            <el-icon>
                              <Document />
                            </el-icon>
                          </template>
                        </el-input>
                      </el-card>
                    </el-form-item>

                    <el-form-item v-if="form.db_type === 'mysql'" class="dsn-form-item">
                      <el-card class="dsn-card">
                        <template #header>
                          <div class="card-header">
                            <span>样例:&nbsp;&nbsp;root:mypwd@tcp(192.168.150.110:3306)/mydb?charset=utf8mb4&parseTime=True&loc=Local</span>
                          </div>
                        </template>
                        <el-input v-model="form.mysql_dbdsn" minlength="10" maxlength="65535" show-word-limit clearable
                          placeholder="请输入数据库DSN,参考上面的样例" class="dsn-input">
                          <template #prefix>
                            <el-icon>
                              <Document />
                            </el-icon>
                          </template>
                        </el-input>
                      </el-card>
                    </el-form-item>

                    <el-form-item v-if="form.db_type === 'pgsql'" class="dsn-form-item">
                      <el-card class="dsn-card">
                        <template #header>
                          <div class="card-header">
                            <span>样例:&nbsp;&nbsp;host=192.168.150.110 port=5432 user=postgres dbname=mydb
                              sslmode=disable password=mypwd</span>
                          </div>
                        </template>
                        <el-input v-model="form.pgsql_dbdsn" minlength="10" maxlength="65535" show-word-limit clearable
                          placeholder="请输入数据库DSN,参考上面的样例" class="dsn-input">
                          <template #prefix>
                            <el-icon>
                              <Document />
                            </el-icon>
                          </template>
                        </el-input>
                      </el-card>
                    </el-form-item>
                  </div>
                </div>

                <div v-if="active === 1" class="form-section">
                  <div class="section-title">账号信息</div>
                  <div class="section-content">
                    <el-form-item label="用户名" required>
                      <el-input v-model="form.name" trim minlength="1" maxlength="64" show-word-limit clearable
                        placeholder="请输入用户名" class="account-input">
                        <template #prefix>
                          <el-icon>
                            <User />
                          </el-icon>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item label="密码" required>
                      <el-input v-model="form.pwd" trim type="password" minlength="3" maxlength="64" show-word-limit
                        show-password clearable placeholder="请输入密码" class="account-input">
                        <template #prefix>
                          <el-icon>
                            <Lock />
                          </el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </div>
                </div>

                <div v-if="active === 2" class="form-section">
                  <div class="section-title">配置确认</div>
                  <div class="section-content">
                    <el-card class="confirm-card">
                      <template #header>
                        <div class="card-header">
                          <span>请妥善保存以下配置信息</span>
                        </div>
                      </template>
                      <div class="confirm-info">
                        <p><strong>数据库类型:</strong> {{ form.db_type === 'pgsql' ? 'PostgreSQL' : 'MySQL' }}</p>
                        <p><strong>数据库DSN:</strong> {{ db_dsn }}</p>
                        <p><strong>账号:</strong> {{ form.name }}</p>
                        <p><strong>密码:</strong> {{ form.pwd }}</p>
                      </div>
                    </el-card>
                  </div>
                </div>

                <div class="form-footer">
                  <el-button type="primary" v-if="active === 0" @click="dbConnCheck" class="action-button">
                    <el-icon>
                      <Connection />
                    </el-icon>测试连接
                  </el-button>
                  <el-button v-if="active > 0" type="default" @click="goPrev" class="action-button">
                    <el-icon>
                      <ArrowLeft />
                    </el-icon>上一步
                  </el-button>
                  <el-button v-if="active < 2" type="primary" @click="goNext" class="action-button">
                    下一步<el-icon>
                      <ArrowRight />
                    </el-icon>
                  </el-button>
                  <el-popconfirm v-if="active === 2" confirmButtonText="确定" cancelButtonText="取消" icon="el-icon-info"
                    iconColor="red" title="确定初始化系统?" @confirm="sysInit">
                    <template #reference>
                      <el-button type="primary" class="action-button">
                        <el-icon>
                          <Check />
                        </el-icon>完成
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
} from "vue";

import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useGlobalStore } from "@/stores/store";
import { Document, User, Lock, Connection, ArrowLeft, ArrowRight, Check } from '@element-plus/icons-vue';


let globalStore = useGlobalStore();
let router = useRouter();


const form = reactive({
  sqlite_dbdsn: "",
  mysql_dbdsn: "",
  pgsql_dbdsn: "",
  db_type: "mysql",
  name: "",
  pwd: ""
})

let db_dsn = computed<string>(() => {
  if (form.db_type == "mysql") {
    return form.mysql_dbdsn
  }
  if (form.db_type == "pgsql") {
    return form.pgsql_dbdsn
  }
  if (form.db_type == "sqlite") {
    return form.sqlite_dbdsn
  }
  return "";
})

const active = ref<number>(0)

const goPrev = () => {
  if (active.value-- < 0) {
    active.value = 0

  }
}
const goNext = () => {
  if (active.value++ > 2) {
    active.value = 0
  }
}

interface ResponseData {
  code: number;
  msg: string;
  data?: any
}

function dbConnCheck() {
  let str = db_dsn.value.trim();
  if (str.length < 10) {
    ElMessage.error("请输入正确配置")
    return;
  }
  axios.post<ResponseData>(`/api/sys/db_conn_check`,
    { "db_type": form.db_type, "db_dsn": str }
  ).then((ret) => {
    if (ret.data.code === 0) {
      ElMessage.success("连接数据库成功");
    } else {
      ElMessage.error("连接数据库错误:" + ret.data.msg)
    }
  }).catch((ret) => {
    ElMessage.error("连接数据库错误异常");
  })
}

function randomString(length: number) {
  let result = "";
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

function sysInit() {
  let initData = {
    "db_type": form.db_type,
    "db_dsn": db_dsn.value.trim(),
    "jwt_secret": randomString(64),
    "session_secret": randomString(64),
    "username": form.name.trim(),
    "password": form.pwd.trim()
  }
  if (initData.db_dsn.length < 5) {
    ElMessage.error("系统初始化错误:请输入正确的数据库连接")
    return
  }

  if (initData.username.length < 2) {
    ElMessage.error("系统初始化错误:用户名至少两个字符")
    return
  }

  if (initData.password.length < 2) {
    ElMessage.error("系统初始化错误:密码至少两个字符")
    return
  }

  axios.post<ResponseData>(`/api/sys/init`, initData)
    .then((ret) => {
      if (ret.data.code === 0) {
        ElMessage.success("系统初始化成功");
        globalStore.isInit = true;
        router.push({ "name": "Login" });
      } else {
        ElMessage.error("系统初始化错误:" + ret.data.msg)
      }
    }).catch((ret) => {
      console.log(ret)
      ElMessage.error("系统初始化错误异常");
    })
}

onBeforeMount(() => {
  if (globalStore.isInit) {
    router.push({ "name": "Login" })
  }
})

</script>

<style scoped>
.sys-init-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.sys-init-header {
  padding: 20px 0;
}

.sys-init-header h1 {
  text-align: center;
  color: #1976d2;
  font-weight: 500;
  margin: 0;
}

.sys-init-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
  padding: 20px;
}

.sys-init-steps {
  padding: 20px 0;
}

.sys-init-form {
  margin-top: 20px;
}

.form-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
}

.section-title {
  color: #1976d2;
  font-size: 16px;
  font-weight: 500;
  padding: 12px 20px;
  border-bottom: 2px solid #e8f0fe;
}

.section-content {
  padding: 20px;
}

.section-content :deep(.el-form-item) {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.section-content :deep(.el-form-item__label) {
  height: 45px;
  line-height: 45px;
  padding-right: 20px;
  width: 80px !important;
  justify-content: flex-end;
}

.section-content :deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
  max-width: calc(100% - 80px);
}

.db-type-radio {
  display: flex;
  gap: 20px;
}

.db-type-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #1976d2;
  border-color: #1976d2;
}

.db-type-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #1976d2;
}

.dsn-card {
  margin-top: 15px;
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
}

.dsn-card :deep(.el-card__header) {
  background: #f5f7fa;
  padding: 10px 20px;
}

.dsn-input :deep(.el-input__wrapper),
.account-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 45px;
  line-height: 45px;
}

.dsn-input :deep(.el-input__wrapper:hover),
.account-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.15);
}

.dsn-input :deep(.el-input__prefix-inner),
.account-input :deep(.el-input__prefix-inner) {
  color: #1976d2;
  font-size: 16px;
  height: 45px;
  line-height: 45px;
}

.dsn-input :deep(.el-input__inner),
.account-input :deep(.el-input__inner) {
  height: 45px;
  line-height: 45px;
}

.confirm-card {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
}

.confirm-card :deep(.el-card__header) {
  background: linear-gradient(45deg, #1976d2, #64b5f6);
  color: white;
  padding: 15px 20px;
}

.confirm-info {
  padding: 10px;
}

.confirm-info p {
  margin: 10px 0;
  line-height: 1.6;
}

.confirm-info strong {
  color: #1976d2;
  margin-right: 10px;
}

.form-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid #e8f0fe;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 25px;
  height: 40px;
}

.action-button:deep(.el-button--primary) {
  background: linear-gradient(45deg, #1976d2, #64b5f6);
  border: none;
}

.action-button:deep(.el-button--primary:hover) {
  background: linear-gradient(45deg, #1565c0, #42a5f5);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px 0 rgba(25, 118, 210, 0.25);
}

@media (max-width: 768px) {
  .el-col-16 {
    width: 100%;
  }

  .el-col-4 {
    display: none;
  }

  .section-content {
    padding: 15px;
  }

  .form-footer {
    flex-wrap: wrap;
  }

  .action-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
